import {Button, message, Pagination, Popconfirm, Space, Spin, Table, Tag} from "antd";
import React, {Key, useEffect, useState} from "react";
import {ColumnsType} from "antd/es/table";
import {RandomColor} from "../../utils/ColorUtil";
import {strToTime} from "../../utils/time";
import {
    DeleteOutlined,
    DownloadOutlined,
    RedoOutlined,
    UploadOutlined
} from "@ant-design/icons";
import {ImageItem, ImagesResult} from "../images";
import {HttpGet, PageResult, Post} from "../../utils/http";
import {TableRowSelection} from "antd/es/table/interface";
import {ResourceUpload} from "../../component";

export const DocumentPage = () => {

    const [visible, setVisible] = useState<boolean>(false)
    const [spinning, setSpinning] = useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

    const [dataSource, setDataSource] = useState<ImagesResult>({
        page: 1, limit: 10, total: 0, data: [], cate_id: 7938238054400
    })

    const columns:ColumnsType<ImageItem> = [
        {
            key: 'title',
            dataIndex: 'title',
            title: '名称',
            ellipsis: true,
            align: 'center',
            width: '20%'
        },
        {
            key: 'tags',
            dataIndex: 'tags',
            title: '标签',
            align: 'center',
            width: '30%',
            render: (tags, record) => <Space>
                {tags.length > 0 && tags.split(",").map((item:string, index:number) => <Tag key={index} color={RandomColor()}>{item}</Tag>)}
            </Space>
        },
        {
            key: 'format',
            dataIndex: 'format',
            title: '格式',
            align: 'center',
            width: '10%'
        },
        {
            key: 'file_size',
            dataIndex: 'file_size',
            title: '大小',
            align: 'center',
            width: '10%'
        },
        {
            key: 'create_time',
            dataIndex: 'create_time',
            title: '时间',
            align: 'center',
            width: '15%',
            ellipsis: true,
            render: (create_time) => <span>{strToTime(create_time)}</span>
        },
        {
            key: 'active',
            title: '操作',
            align: 'center',
            width: '10%',
            render: (text, record, index) => <Space>
                <Button icon={<DownloadOutlined />} type={"primary"} size={"small"} onClick={() => downloadFile(record.original_url)} />
                <Popconfirm
                    placement="topRight"
                    title="删除当前图片可在回收站中恢复，确认删除？"
                    onConfirm={() => deleteDocument([record.id])}
                    okText="确定"
                    cancelText="取消"
                ><Button icon={<DeleteOutlined />} type={"primary"} size={"small"} danger /></Popconfirm>

            </Space>
        }
    ]

    const deleteDocument = (id:number[]) => {
        setSpinning(true)
        HttpGet<boolean>('/api/resources/delete', {cate_id: 7938238054400, ids: id.join(",")}).then(res => {
            setSpinning(false)
            if (res.code === '100200') {
                loadDocument(dataSource.page, dataSource.limit)
                message.success('删除成功')
            } else {
                message.error(res.msg)
            }
        })
    }

    const loadDocument = (page: number, limit: number) => {
        setSpinning(true)
        Post<PageResult<ImageItem>>('/api/resources/page', {page: page, limit: limit, cate_id: dataSource.cate_id}).then(res => {
            setSpinning(false)
            if (res.code === '100200') {
                console.log(res.data)
                setDataSource({
                    ...dataSource,
                    page: page,
                    limit: limit,
                    total: res.data.total,
                    data: res.data.content
                })
            } else {
                message.error(res.msg)
            }
        })
    }

    useEffect(() => {
        loadDocument(1, 10)
    }, [])

    const rowSelection: TableRowSelection<ImageItem> = {
        selectedRowKeys,
        onChange: (selectedRowKeys: Key[], selectedRows: ImageItem[]) => {
            const ids = selectedRows.map(item => item.id)
            setSelectedRowKeys(ids)
        },
    };

    const closeModel = (refresh: boolean) => {
        setVisible(false)
        if (refresh) {
            loadDocument(dataSource.page, dataSource.limit)
        }
    }


    const downloadFile = (url: string) => {
        window.open(url, '_blank')
    }

    return <div style={{paddingTop: '5px'}}>
        <Space style={{marginBottom: '8px'}}>
            <Button type="primary" size={'small'} icon={<UploadOutlined />} onClick={() => setVisible(true)}>上传文档</Button>
            <Popconfirm
                placement="topRight"
                title="删除当前图片可在回收站中恢复，确认删除？"
                onConfirm={() => deleteDocument(selectedRowKeys)}
                okText="确定"
                cancelText="取消">
                <Button type="primary" size={'small'} icon={<DeleteOutlined />} danger>批量删除</Button>
            </Popconfirm>
            <Button
                type="primary"
                size={'small'}
                icon={<RedoOutlined />}
                style={{borderColor: '#fa8c16', backgroundColor: '#fa8c16'}}
                onClick={() => loadDocument(dataSource.page, dataSource.limit)}
            >
                刷新
            </Button>
        </Space>
        <Spin tip="Loading..." spinning={spinning}>
            <Table
                bordered
                size={'small'}
                columns={columns}
                dataSource={dataSource.data}
                rowSelection={rowSelection}
                rowKey={record => record.id}
                pagination={false}
            />
            <Pagination
                style={{marginTop: 8, textAlign: 'right'}}
                showSizeChanger
                defaultCurrent={1}
                total={dataSource.total}
            />
        </Spin>
        <ResourceUpload
            visible={visible}
            type={"document"}
            cate_id={7938238054400}
            onCancel={(refresh) => closeModel(refresh)} />
    </div>
}